package com.xzixi.websocket.interceptablewebsocket.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xzixi.websocket.interceptablewebsocket.exception.InterceptableWebsocketException;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;

import java.io.IOException;

/**
 * @author 薛凌康
 */
@Component
public class NotifyUtil {

    private ObjectMapper objectMapper = new ObjectMapper();

    public void sendMessage(WebSocketSession session, Object message) {
        if (message==null) {
            return;
        }
        String content;
        if (message instanceof String) {
            content = message.toString();
        } else {
            try {
                content = objectMapper.writeValueAsString(message);
            } catch (JsonProcessingException e) {
                throw new InterceptableWebsocketException("json转换出错", e);
            }
        }
        ConcurrentWebSocketSessionDecorator decorator = new ConcurrentWebSocketSessionDecorator(session, -1, -1);
        try {
            decorator.sendMessage(new TextMessage(" "+content));
        } catch (IOException e) {
            throw new InterceptableWebsocketException("发送消息出错", e);
        }
    }

}
